package com.cdbkj.cloud.pos.fragment;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.androidyang.library.common.utils.GsonUtils;
import com.androidyang.library.http.okhttp.bean.HttpResult;
import com.androidyang.library.http.okhttp.listener.HttpClientHandler;
import com.cdbkj.cloud.pos.MainActivity;
import com.cdbkj.cloud.pos.R;
import com.cdbkj.cloud.pos.bean.JsonResult;
import com.cdbkj.cloud.pos.http.HttpRequest;
import com.cdbkj.cloud.pos.utils.Tools;
import com.dawn.cloud.pos.drive.bean.BmpRequestSale;
import com.dawn.cloud.pos.drive.bean.BmpRequestVoid;
import com.dawn.cloud.pos.drive.bean.BmpResponseSale;
import com.dawn.cloud.pos.drive.bean.BmpResponseVoid;
import com.dawn.cloud.pos.drive.sdk.BmpSdk;
import com.orhanobut.logger.Logger;

import org.json.JSONException;
import org.json.JSONObject;

import java.math.BigDecimal;
import java.util.Map;

public class BankCardFragment extends Fragment {
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    private static final String ARG_PARAM3 = "param3";
    private static final String ARG_PARAM4 = "param4";

    private String userId;
    private String amount;

    //配对蓝牙名称
    private String bluetoothName;
    //配对款台号
    private String counterNo;
    //流水号
    private String traceNo;
    //凭证号
    private String voucherNo;

    private TextView temTV;

    protected View rootView;
    protected int connectCount = 0;
    protected Runnable connectRunnable;
    protected Runnable sendDataRunnable;

    private OnBankCardFragmentInteractionListener mListener;

     //==================mis pos 蓝牙支付 相关================================

     private BmpSdk bmpSdk;
     private String serverData;//服务器端数据
     //private boolean running = true;
     private BmpResponseSale responseSale;
     //==============================================================

    public BankCardFragment() {
        // Required empty public constructor
    }

    public static BankCardFragment newInstance(String userId, String amount,String bluetoothName,String counterNo) {
        BankCardFragment fragment = new BankCardFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, userId);
        args.putString(ARG_PARAM2, amount);
        args.putString(ARG_PARAM3, bluetoothName);
        args.putString(ARG_PARAM4, counterNo);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            userId = getArguments().getString(ARG_PARAM1);
            amount = getArguments().getString(ARG_PARAM2);
            bluetoothName = getArguments().getString(ARG_PARAM3);
            counterNo = getArguments().getString(ARG_PARAM4);
        }
        temTV = new TextView(getActivity());
        View.OnClickListener clickListener = new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Tools.dismissDialog();
                misposSocketConnect();
            }
        };
        View.OnClickListener cancelClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Tools.dismissDialog();
                Intent intent = new Intent(getActivity(),MainActivity.class);
                startActivity(intent);
            }
        };
        Tools.showDialog("请确认刷卡设备蓝牙已经打开！",getActivity(),cancelClickListener,clickListener);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        bmpSdk.shutdownClient();
        Logger.d("bmpSdk.shutdownClient()");
        temTV.removeCallbacks(sendDataRunnable);
        Logger.d("sendDataRunnable stop");
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_bank_card, container, false);
        return rootView;
    }


    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnBankCardFragmentInteractionListener) {
            mListener = (OnBankCardFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnBankCardFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

     public interface OnBankCardFragmentInteractionListener {
        void onBankCardFragmentInteraction(String posTransNo,String openBank,String openAccount);
        void returnSelectPayWay();
        void onBankCardRescissionInteraction(String status);
    }

     /**
      * mis pos 蓝牙 连接 刷卡设备
      */
     public void misposSocketConnect(){
         if(bmpSdk==null){
             return;
         }
         bmpSdk.open(bluetoothName);
         //设备被发现广播  蓝牙扫描时，扫描到任一远程蓝牙设备时，会发送此广播。给onreceive
         IntentFilter discoveryFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
         getActivity().registerReceiver(bmpSdk, discoveryFilter);
         // 设备发现完成  蓝牙扫描过程结束
         IntentFilter foundFilter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
         getActivity().registerReceiver(bmpSdk, foundFilter);
         bmpSdk.discovery();

         //监听是否已 连接到蓝牙设备
         connectRunnable = new Runnable() {
             @Override
             public void run() {
                 if(connectCount>=20){
                     temTV.removeCallbacks(connectRunnable);
                     Tools.showDialogWithReturnMainActivity("请确认银行卡刷卡设备蓝牙是否已打开？",getActivity());
                     return;
                 }
                 Logger.d("mSocketConnect = " + bmpSdk.getmSocketConnect());
                 //Logger.d("mConnect = " + mConnect);
                 while (bmpSdk.getmSocketConnect()){
                     temTV.removeCallbacks(connectRunnable);
                     connectCount = 0;
                     sale();
                     return;
                 }
                 connectCount++;
                 //每1秒执行一次
                 temTV.postDelayed(this, 1000);
             }
         };
         temTV.postDelayed(connectRunnable,1000);
     }

     /**
      * 消费
      */
     private void sale() {
         if(!bmpSdk.getmSocketConnect()){
             Toast.makeText(getActivity().getApplicationContext(), "蓝牙服务未连接", Toast.LENGTH_LONG).show();
             Logger.d("蓝牙服务未连接");
             misposSocketConnect();
             return;
         }
         String resData = "";
         BmpRequestSale bmpRequestSale = new BmpRequestSale();
         BigDecimal b1 = new BigDecimal(amount);
         BigDecimal b2 = b1.multiply(new BigDecimal(100));
         String money = String.valueOf(b2.intValue());
         int len = 12-money.length();
         for (int i=0;i<len;i++){
             money = "0"+money;
         }
         amount = money;
         bmpRequestSale.setAmount(amount);
         bmpRequestSale.setTransID("消费");
         bmpRequestSale.setOpID(userId);
         bmpRequestSale.setCounterNo(counterNo);
         resData = GsonUtils.toJson(bmpRequestSale);
         Logger.d("发送消息:" + resData);
         bmpSdk.sendMessage(resData);
         sendDataRunnable = new Runnable() {
             @Override
             public void run() {
                 if(connectCount>20){
                     temTV.removeCallbacks(sendDataRunnable);
                     Tools.showDialogWithReturnMainActivity("交易失败，请重新尝试，或选择其他支付方式",getActivity());
                     return;
                 }
                 serverData = bmpSdk.getServerData();
                 if(serverData!=null && !"".equals(serverData)){
                     temTV.removeCallbacks(sendDataRunnable);
                     Logger.d("服务端返回："+serverData);
                     try {
                         JSONObject json = new JSONObject(serverData);

                         /**
                          * 交易是否成功标示，00   -----成功 其他 -----失败
                          */
                         String respCode = json.optString("respCode");
                         /**
                          * 发卡机构
                          */
                         String openBank = json.optString("cardIssuer");
                         /**
                          * 卡号
                          */
                         String openAccount = json.optString("pan");

                         /**
                          * 流水号
                          */
                         traceNo = json.optString("traceNo");
                         /**
                          * 凭证号
                          */
                         voucherNo = json.optString("voucherNo");
                         /**
                          * 批次号
                          */
                         String batchNo = json.optString("batchNo");
                         /**
                          * 参考号
                          */
                         String rrn = json.optString("rrn");
                         /**
                          * 终端号
                          */
                         String termID = json.optString("termID");
                         /**
                          * 商户号
                          */
                         String mrchID = json.optString("mrchID");
                         /**
                          * 交易日期
                          */
                         String transDate = json.optString("transDate");
                         /**
                          * 交易时间
                          */
                         String transTime = json.optString("transTime");

                         String posTransNo = traceNo + "|" + batchNo + "|" + rrn + "|" + termID + "|" + mrchID + "|" + transDate + "|" + transTime;

                         if("00".equals(respCode)){
                             mListener.onBankCardFragmentInteraction(posTransNo,openBank,openAccount);
                         }
                         else {
                             View.OnClickListener clickListener = new View.OnClickListener() {
                                 @Override
                                 public void onClick(View view) {
                                     mListener.returnSelectPayWay();
                                     Tools.dismissDialog();
                                 }
                             };
                             Tools.showDialog("交易失败，请重新尝试！",getActivity(),clickListener,clickListener);
                         }
                     } catch (JSONException e) {
                         e.printStackTrace();
                     }
                     serverData = "";
                     temTV.removeCallbacks(sendDataRunnable);
                     return;
                 }
                 connectCount++;
                 //每10秒执行一次
                 temTV.postDelayed(this, 1000);
             }
         };
         temTV.postDelayed(sendDataRunnable,0);
     }

    /**
     * 撤销
     */
    public void rescission(){
        BmpRequestVoid bmpRequestVoid = new BmpRequestVoid();
        bmpRequestVoid.setAmount(amount);
        bmpRequestVoid.setCashierID(traceNo);
        bmpRequestVoid.setCounterNo(counterNo);
        bmpRequestVoid.setOpID(userId);
        bmpRequestVoid.setOrgVoucherNo(voucherNo);
        String resData = GsonUtils.toJson(bmpRequestVoid);
        Logger.d("发送消息:" + resData);
        bmpSdk.sendMessage(resData);
        sendDataRunnable = new Runnable() {
            @Override
            public void run() {
                serverData = bmpSdk.getServerData();
                if(serverData!=null && !"".equals(serverData)){
                    temTV.removeCallbacks(sendDataRunnable);
                    Logger.d("服务端返回："+serverData);
                    BmpResponseVoid bmpResponseVoid = GsonUtils.parseJson(serverData,BmpResponseVoid.class);

                    if("00".equals(bmpResponseVoid.getRespCode())){
                        mListener.onBankCardRescissionInteraction("Y");
                        Tools.showDialogWithReturnMainActivity("his处理失败，金额已退回到您的银行卡",getActivity());
                    }
                    else {
                        mListener.onBankCardRescissionInteraction("N");
                        Tools.showDialogWithReturnMainActivity("his处理失败，银行卡退费失败，请联系管理员！",getActivity());
                    }
                    serverData = "";
                    temTV.removeCallbacks(sendDataRunnable);
                    return;
                }
                connectCount++;
                //每10秒执行一次
                temTV.postDelayed(this, 1000);
            }
        };
        temTV.postDelayed(sendDataRunnable,0);

    }

     public void setBmpSdk(BmpSdk bmpSdk) {
         this.bmpSdk = bmpSdk;
     }
 }
